package com.lzh.hosp.config;

import com.lzh.hosp.filter.DoctorAuthFilter;
import com.lzh.hosp.filter.JwtAuthenticationTokenFilter;
import com.lzh.hosp.handler.JwtLogoutSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true,
        jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    JwtAuthenticationTokenFilter jwtAuthenticationFilter() throws Exception {
        JwtAuthenticationTokenFilter jwtAuthenticationFilter = new JwtAuthenticationTokenFilter(authenticationManager());
        return jwtAuthenticationFilter;
    }

    @Autowired
    private DoctorAuthFilter doctorAuthFilter;

    @Autowired
    JwtLogoutSuccessHandler jwtLogoutSuccessHandler;

    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    private AccessDeniedHandler accessDeniedHandler;

    public static final String[] URL_WHITELIST = {
            "/dict/findChildData/**",
            "/sys/user/sendCode/**",
            "/sche/findByDepcodeAndWorkDate",
            "/patient/findFromRedis/*",
            "/patient/findMedicatedPatientList/**",
            "/patient/findOvertimePatientByDepcode/**",
            "/patient/findWaitPatientList/**",
            "/file/fileUpload",
            "/prescription/test",
            "/api/**",
            "/socket.io/**",
            "/swagger-resources/configuration/ui",
            "/swagger-resources",
            "/swagger-resources/configuration/security",
            "/swagger-ui.html",
            "/css/**",
            "/js/**",
            "/patient/findVisitPatient/*",
            "/swagger-ui/**",
            "/v3/api-docs/**"
    };


    @Override
    public void configure(WebSecurity web) throws Exception {
        //放行静态资源
        web.ignoring().antMatchers(
                "/ws/**",
                "/v2/api-docs",
                "/swagger-resources/configuration/ui",
                "/swagger-resources",
                "/swagger-resources/configuration/security",
                "/swagger-ui.html",
                "/css/**",
                "/js/**",
                "/images/**",
                "/webjars/**",
                "/import/test",
                "**/favicon.ico",
                "/index");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //关闭csrf
                .csrf().disable()
                .cors()
                .and()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 对于登录接口 允许匿名访问
                .antMatchers(
                        "/sys/user/register/**",
                        "/sys/user/login",
                        "/sys/user/phoneLogin"
                        ).anonymous()//表示匿名可访问
                .antMatchers(URL_WHITELIST).permitAll()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();

                http.addFilter(jwtAuthenticationFilter());
                http.addFilterAfter(doctorAuthFilter,JwtAuthenticationTokenFilter.class);

                //异常处理
                http.exceptionHandling()
                    .authenticationEntryPoint(authenticationEntryPoint)
                    .accessDeniedHandler(accessDeniedHandler);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder(){
            final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            @Override public boolean matches(CharSequence rawPassword, String encodedPassword) {
                return encoder.matches(rawPassword, encodedPassword)||rawPassword.equals(encodedPassword);
            }
        };
    }
}
